<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单名称" prop="workOrderName">
        <el-input v-model="queryParams.workOrderName" placeholder="请输入工单名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单编号" prop="workOrderNo">
        <el-input v-model="queryParams.workOrderNo" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单状态" prop="workOrderStauts">
        <el-select v-model="queryParams.workOrderStauts" placeholder="请选择工单状态" clearable>
          <el-option v-for="dict in workStauts" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <div style="float: right">
        <el-button v-if="showButton" type="primary" icon="el-icon-s-claim" @click="kaiGong()" :disabled="!canStartWork || isButtonClicked ">
          开始调度
        </el-button>
      </div>
    </el-form>
    <el-table v-loading="loading" :data="workorderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" :index="indexMethod" />
      <el-table-column label="ID" align="center" prop="id" v-if="showIdColumn1"></el-table-column>
      <el-table-column label="添加人数" align="center" prop="extraPer" v-if="showIdColumn"></el-table-column>
      <el-table-column label="工单名称" align="center" prop="workOrderName" width="300"  />
      <el-table-column label="工单编号" align="center" prop="workOrderNo" width="150" />
      <el-table-column label="工序名称" align="center" prop="processName" width="100" />
      <el-table-column label="第几辆车" align="center" prop="ji" width="80" />
      <el-table-column label="第几道工序" align="center" prop="productionLineSequence" width="90" />
      <el-table-column label="添加人员" align="center" prop="peopleNames" width="180" />
      <el-table-column label="工单状态" align="center" prop="workOrderStauts" :formatter="workStautsFomatter" />
      <el-table-column label="预计开始时间" align="center" prop="exStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.exStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计完成时间" align="center" prop="exEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.exEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际开始时间" align="center" prop="acStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.acStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际结束时间" align="center" prop="acEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.acEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-if="scope.row.peopleNames == null || scope.row.peopleNames == '' "
                     @click="handleUpdate(scope.row)"> 调度加人 </el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />-->
    <!-- 修改任务工单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单名称" prop="workOrderName">
          <el-input v-model="form.workOrderName" placeholder="请输入工单名称" disabled />
        </el-form-item>
        <el-form-item label="工单编号" prop="workOrderNo">
          <el-input v-model="form.workOrderNo" placeholder="请输入工单编号" disabled />
        </el-form-item>
        <el-form-item label="工序编号" prop="processNo">
          <el-input v-model="form.processNo" placeholder="请输入工序编号" disabled />
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="form.processName" placeholder="请输入工序名称" disabled />
        </el-form-item>
        <el-form-item label="人员">
          <el-checkbox-group v-model="peopleIds" @change="handleCheckboxChange">
            <el-checkbox v-for="p in peopleList" :label="p.id" :value="p.id" v-bind:key="p.id">{{p.employeeName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask } from "@/api/zndd/task/task";
import { kaiGong, listJiuXu, peopleShang, peoplesList } from '@/api/zndd/intelligence/jiaren';

export default {
  name: "jiaren",
  props: ['showButton','isFromIndex'],
  data() {
    return {
      isButtonClicked: false,
      buttonStates: [], // 用于记录每个调度加人按钮的操作状态
      // 允许选中的最大个数
      maxSelected: 0,
      peopleIds: [],
      showIdColumn: false,
      showIdColumn1: false,
      peopleList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 作业类型列表
      workStauts: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务工单信息表格数据
      workorderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前Id
      currentTaskId: null,
      taskParams: {
        pageNum: 1,
        pageSize: 50,
        deptId: null,
        taskParam: null
      },
      taskList: [],
      // 查询参数
      queryParams: {
       /*  pageNum: 1,
        pageSize: 10, */
        deptId: null,
        mesNo: null,
        taskNo: null,
        taskId: null,
        processId: null,
        workOrderName: null,
        workOrderNo: null,
        workOrderStauts: null,
        exStartTime: null,
        exEndTime: null,
        sexStartTime: null,
        sexEndTime: null,
        acStartTime: null,
        acEndTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      selectedTime: '30秒钟',
      currentTaskName: null,
      processType: null,
    };
  },
  computed: {
    timeInMilliseconds() {
      const seconds = parseInt(this.selectedTime.replace('秒钟', ''), 10);
      return seconds * 1000;
    },
    // 计算属性判断是否可以点击开工
    canStartWork() {
      return this.workorderList.every(row =>!(row.peopleNames == null || row.peopleNames == ''));
    }
  },
  created() {
    this.getTaskList11();
    // 获取字典表中工单状态
    this.getDicts("zndd_worker_order_status").then(response => {
      this.workStauts = response.data;
      if (this.workStauts.length > 0) {
        this.queryParams.workOrderStauts = this.workStauts[1].dictValue;
      }
      this.getList();
    });
    if (!this.isFromIndex) {
      this.startTimer();
    }
    // 初始化定时器
    // this.startTimer();
    // 初始化 buttonStates 数组
    this.workorderList.forEach(() => this.buttonStates.push(true));
  },
  beforeDestroy() {
    // 清除定时器
    this.clearTimer();
  },
  watch: {
    selectedTime() {
      // 当 selectedTime 改变时，重新设置定时器
      this.resetTimer();
    },
  },
  methods: {
    // 父组件调用子组件方法  向子组件传递参数
    jrMethods() {
      this.getList();
    },
    // 定时器相关
    startTimer() {
      this.timer = setInterval(() => {
        this.getList();
      }, this.timeInMilliseconds);
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    resetTimer() {
      this.clearTimer();
      this.startTimer();
    },
    handleCheckboxChange() {
      // 检查选中的个数是否超出最大限制
      if (this.peopleIds.length > this.maxSelected) {
        this.peopleIds.pop();
        this.$message.warning('最多选中'+ this.maxSelected +'个人员');
      }
    },
    // 获取人员
    getEmployeeList() {
      peoplesList().then(res => {
        this.peopleList = res;
      });
    },
    kaiGong() {
      console.log("开工");
      kaiGong().then(response => {
        if (this.isButtonClicked) {
          this.$message.warning('任务已经开工');
          return;
        }
        if (response.code == 500) {
          this.$message.error(response.msg);
        } else {
          this.$message.success("调度完成");
          this.isButtonClicked = true;
          // 触发自定义事件通知父组件关闭抽屉
          this.$emit('closeDrawer');
        }

      });
    },
    /** 序号 */
    indexMethod(index) {
        return index + 1;
    },
    getTaskList11() {
      var param = { pageNum: 1, pageSize: 100 };
      listTask(param).then(response => {
        this.taskList = response.rows;
      });
    },
    // 格式化工单状态
    workStautsFomatter(row, column) {
      var ws = null;
      this.workStauts.forEach(workStauts => {
        if (workStauts.dictValue == row.workOrderStauts) {
          ws = workStauts;
        }
      });
      if (ws == null) {
        return "";
      } else {
        if (ws.dictValue == 1) {
          return <el-tag type="danger">未就绪</el-tag>;
        } else if (ws.dictValue == 2) {
          return <el-tag>就绪</el-tag>;
        } else if (ws.dictValue == 3) {
          return <el-tag type="success">进行中</el-tag>;
        } else if (ws.dictValue == 4) {
          return <el-tag type="info">已完成</el-tag>;
        } else if (ws.dictValue == 5) {
          return <el-tag type="warning">异常</el-tag>;
        }
        return ws.dictLabel;
      }
    },
    /** 查询任务工单信息列表 */
    getList() {
      this.loading = true;
      listJiuXu(this.queryParams).then(response => {
        this.workorderList = response;
        // this.total = response.total;
        this.loading = false;
        // 更新 buttonStates 数组
        this.buttonStates = response.map(row =>!(row.peopleNames == null || row.peopleNames == ''));
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        mesNo: null,
        taskNo: null,
        taskId: null,
        processId: null,
        workOrderName: null,
        workOrderNo: null,
        workOrderStauts: null,
        exStartTime: null,
        exEndTime: null,
        sexStartTime: null,
        sexEndTime: null,
        acStartTime: null,
        acEndTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!== 1;
      this.multiple =!selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row);
      this.form = row;
      this.getEmployeeList();
      console.log(row.processNo);
      this.maxSelected = row.extraPer;
      this.peopleIds = [];
      this.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      if(this.peopleIds.length!=this.maxSelected){
        this.$message.warning('需要选中 ' + this.maxSelected + ' 个人员');
        return;
      }
      this.form.peoIds=this.peopleIds;
      console.log(this.form)
      peopleShang(this.form).then(response => {
        this.$modal.msgSuccess("加人成功");
        this.open = false;
        this.getList();
      });
    },

  }
};
</script>

<style lang="css" scoped>

</style>
